<template>
	<view class="container">
		<!-- 空状态栏占位 -->
		
		
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input">
				<text class="search-icon">🔍</text>
				<input type="text" placeholder="资产名称" v-model="searchKeyword" @input="onSearchInput" />
			</view>
		</view>
		
		<view class="status-bar"></view>
		
		<!-- 草稿列表 -->
		<view class="drafts-list">
			<!-- 使用相对定位的容器实现左滑效果 -->
			<view class="draft-item" 
				v-for="(draft, index) in filteredDrafts" 
				:key="index" 
				:data-index="index" 
				@touchstart="onTouchStart" 
				@touchmove="onTouchMove" 
				@touchend="onTouchEnd"
			>
				<!-- 内容区域 - 可左滑 -->
				<view class="draft-content" 
					@click="viewDraft(draft)"
					:style="{ transform: `translateX(${draft.translateX}px)` }"
				>
					<view class="draft-header">
						<text class="draft-title">{{ draft.orderNo || '暂无单号' }}</text>
						<view class="status-badge draft">
							<text class="status-text">草稿</text>
						</view>
					</view>
					<view class="draft-info">
						<text class="info-item">资产名称: {{ draft.assetName }}</text>
						<text class="info-item">资产位置: {{ draft.assetLocation }}</text>
						<text class="info-item">发生时间: {{ draft.occurrenceTime }}</text>
					</view>
					<view class="draft-footer">
						<view class="reporter-info">
							<image class="reporter-avatar" :src="draft.reporterAvatar || '/static/个人头像.png'"></image>
							<text class="reporter-name">{{ draft.reporterName }}</text>
						</view>
						<text class="report-time">报修时间: {{ draft.reportTime }}</text>
					</view>
				</view>
				
				<!-- 左滑显示的操作按钮 -->
				<view class="swipe-actions">
					<button class="swipe-btn view" @click.stop="viewDraft(draft)">查看</button>
					<button class="swipe-btn delete" @click.stop="deleteDraft(draft, index)">删除</button>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="filteredDrafts.length === 0">
			<text class="empty-icon">📝</text>
			<text class="empty-text">暂无草稿</text>
		</view>
	</view>
</template>

<script>
	import { listFaultReport, delFaultReport } from '@/api/repair/faultReport.js';
	
	export default {
		data() {
			return {
				searchKeyword: '',
				drafts: [],
				touchStartX: 0,
				touchStartY: 0,
				loading: false
			}
		},
		computed: {
			filteredDrafts() {
				if (!this.searchKeyword) {
					return this.drafts;
				}
				return this.drafts.filter(draft => 
					(draft.assetName && draft.assetName.toLowerCase().includes(this.searchKeyword.toLowerCase())) ||
					(draft.reportNo && draft.reportNo.toLowerCase().includes(this.searchKeyword.toLowerCase()))
				);
			}
		},
		onLoad() {
			this.checkLoginStatus();
			this.loadDrafts();
		},
		onShow() {
			// 检查是否需要刷新
			const needRefresh = uni.getStorageSync('needRefreshDrafts');
			if (needRefresh) {
				this.loadDrafts();
				uni.removeStorageSync('needRefreshDrafts');
			}
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			},
			
			// 加载草稿列表
			async loadDrafts() {
				if (this.loading) return;
				
				this.loading = true;
				try {
					const res = await listFaultReport({
						status: 'DRAFT',
						pageNum: 1,
						pageSize: 100
					});
					
					if (res && res.code === 200 && res.rows) {
						// 过滤出草稿状态的数据
						const draftItems = res.rows.filter(item => item.status === 'DRAFT');
						
						this.drafts = draftItems.map(item => ({
							reportNo: item.reportNo,
							orderNo: item.reportNo,
							assetNo: item.assetNo,
							assetName: item.assetName,
							assetLocation: item.location,
							occurrenceTime: item.occurTime,
							reporterName: item.reporter,
							reporterAvatar: '/static/个人头像.png',
							reportTime: item.reportTime || item.createTime,
							faultDescription: item.faultDescription,
							status: item.status,
							translateX: 0
						}));
						
						console.log('草稿列表加载完成，共', this.drafts.length, '条');
					}
				} catch (error) {
					console.error('加载草稿列表失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
		},
		
		// 搜索输入
			onSearchInput() {
				// 搜索逻辑已在computed中处理
			},
			
			// 触摸开始
			onTouchStart(e) {
				this.touchStartX = e.touches[0].clientX;
				this.touchStartY = e.touches[0].clientY;
			},
			
			// 触摸移动
			onTouchMove(e) {
				const currentX = e.touches[0].clientX;
				const currentY = e.touches[0].clientY;
				const deltaX = currentX - this.touchStartX;
				const deltaY = currentY - this.touchStartY;
				
				// 如果垂直滑动距离大于水平滑动距离，不处理
				if (Math.abs(deltaY) > Math.abs(deltaX)) {
					return;
				}
				
				// 从 data-index 获取索引，更可靠的方式
				const index = parseInt(e.currentTarget.dataset.index);
				
				if (!isNaN(index) && index >= 0 && index < this.filteredDrafts.length) {
					// 限制滑动距离 - 增加到-180px以确保两个按钮都能完全显示
					let translateX = deltaX;
					if (translateX > 0) {
						translateX = 0; // 不能向右滑动
					} else if (translateX < -180) {
						translateX = -180; // 最大向左滑动180px
					}
					
					this.$set(this.filteredDrafts[index], 'translateX', translateX);
				}
			},
			
		// 触摸结束
			onTouchEnd(e) {
				const currentX = e.changedTouches[0].clientX;
				const deltaX = currentX - this.touchStartX;
				
				// 从 data-index 获取索引
				const index = parseInt(e.currentTarget.dataset.index);
				
				if (!isNaN(index) && index >= 0 && index < this.filteredDrafts.length) {
					const draft = this.filteredDrafts[index];
					// 如果滑动距离超过80px，显示操作按钮
					if (deltaX < -80) {
						this.$set(draft, 'translateX', -180); // 修改为-180px以完全显示两个按钮
					} else {
						this.$set(draft, 'translateX', 0);
					}
				}
			},
			
			// 查看草稿详情
			viewDraft(draft) {
				if (!draft.reportNo) {
					uni.showToast({
						title: '草稿数据异常',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: `/pages/repair/detail?reportNo=${draft.reportNo}`
				});
			},
			
			// 临时保存（跳转到详情页）
			tempSave(draft) {
				this.viewDraft(draft);
			},
			
			// 删除草稿
			async deleteDraft(draft, index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个草稿吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '删除中...'
								});
								
								await delFaultReport(draft.reportNo);
								
								// 从列表中移除
								this.drafts.splice(index, 1);
								
								uni.hideLoading();
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							} catch (error) {
								uni.hideLoading();
								console.error('删除草稿失败:', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			}
		}
	}
</script>

<style>
	/* 搜索栏 */
	.search-bar {
		padding: 12px 15px;
		background-color: #f8f8f8;
	}

	.search-input {
		display: flex;
		align-items: center;
		background-color: white;
		border-radius: 6px;
		padding: 8px 15px;
	}

	.search-icon {
		margin-right: 10px;
		font-size: 16px;
		color: #999;
	}

	.search-input input {
		flex: 1;
		font-size: 14px;
		border: none;
		outline: none;
	}

	/* 草稿列表 */
	.drafts-list {
		padding: 10px 15px;
	}

	/* 草稿项容器 - 相对定位 */
	.draft-item {
		position: relative;
		margin-bottom: 12px;
		height: auto; /* 高度自适应内容 */
		overflow: hidden;
		border-radius: 6px;
	}

	/* 草稿内容 - 可左滑的部分 */
	.draft-content {
		position: relative;
		z-index: 1;
		background-color: white;
		border-radius: 6px;
		padding: 12px 15px;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
		transition: transform 0.3s ease;
	}

	.draft-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8px;
	}

	.draft-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		flex: 1;
	}
	
	.status-badge {
		padding: 4px 12px;
		border-radius: 12px;
		font-size: 12px;
	}
	
	.status-badge.draft {
		background-color: #fff3e0;
		color: #ff9800;
	}
	
	.status-text {
		font-size: 12px;
		font-weight: bold;
	}

	.draft-info {
		margin-bottom: 15px;
	}

	.info-item {
		display: block;
		font-size: 14px;
		color: #666;
		margin-bottom: 5px;
	}

	.draft-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.reporter-info {
		display: flex;
		align-items: center;
	}

	.reporter-avatar {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		margin-right: 8px;
		background-color: #f0f0f0;
	}

	.reporter-name {
		font-size: 14px;
		color: #333;
	}

	.report-time {
		font-size: 12px;
		color: #999;
	}

	/* 左滑操作按钮区域 */
	.swipe-actions {
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		z-index: 0;
	}

	/* 左滑操作按钮 */
	.swipe-btn {
		padding: 0 30px; /* 增加按钮宽度，确保文字完全显示 */
		height: 100%;
		font-size: 14px;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		min-width: 90px; /* 添加最小宽度，确保按钮有足够空间 */
	}

	.swipe-btn.view {
		background-color: #2196f3;
	}

	.swipe-btn.delete {
		background-color: #f44336;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40px 20px;
	}

	.empty-icon {
		font-size: 48px;
		margin-bottom: 15px;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 16px;
		color: #999;
	}
</style>
